﻿#include "MainWindow.h"
#include "ui_MainWindow.h"

#include "RtmpPushStream.h"





MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
    , m_image_width(0)
    , m_image_height(0)
{
    ui->setupUi(this);

    QString filePath = QCoreApplication::applicationDirPath() + "/test.h264";

#if 1

    connect(&fileReader, &ChunkFileReader::chunkReady, this,&MainWindow::slotChunkReady);
    connect(&fileReader, &ChunkFileReader::finished, this,&MainWindow::slotFinished);
    fileReader.start(filePath);

#endif

#if 0

    QFile file(filePath);
    if(file.open(QIODevice::ReadOnly))
    {
        QByteArray fileData = file.readAll();
        QList<AVPacket> packetList = h264Parser.parserPacket(fileData);
        file.close();

        for(const auto& packet : packetList)
        {
             h264Parser.decodePacket2Frame(packet);
        }
    }
#endif

#if 1

    m_rtmpPush = new RtmpPushStream(this);

    m_pullStream = new PullStream(this);
    connect(m_pullStream, &PullStream::emitImage, this, &MainWindow::showVideo, Qt::QueuedConnection);

#endif

//    // 初始化 glog
//    google::InitGoogleLogging("glog_demo");

//    // 设置日志文件路径
//    //FLAGS_log_dir = "./logs/";
//    // 设置日志文件路径
//    google::SetLogDestination(google::GLOG_INFO, "./logs/log_");

//    // 设置最低日志级别为 INFO
//    FLAGS_minloglevel = /*google::INFO*/0;

//    // 写入不同级别的日志
//    LOG(INFO) << "This is an INFO message";
//    LOG(WARNING) << "This is a WARNING message";
//    LOG(ERROR) << "This is an ERROR message";

//    //ffmpegPush->init();

//    google::FlushLogFiles(0); // 强制刷新 INFO 级别及以上的日志
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::slotChunkReady(const QByteArray &chunk)
{
    h264Parser.inputData(chunk);
    QList<AVPacket*> packetList = h264Parser.parserPacket();
    for (const auto& packet : packetList) {

        int imageWidth = 0, imageHeight = 0;
        h264Parser.decodePacket2Frame(*packet,imageWidth,imageHeight);
        // 表示图片尺寸有变化
        if(imageWidth > 0 && imageHeight > 0 &&((imageWidth != m_image_width) || (imageHeight != m_image_height)))
        {
            m_image_width = imageWidth;
            m_image_height = imageHeight;
            m_rtmpPush->update_encoder_and_stream(imageWidth, imageHeight);
            m_rtmpPush->init();
        }

        if(m_image_width > 0 && m_image_height > 0)
            m_rtmpPush->addPacket(packet);
    }
}

void MainWindow::slotFinished()
{
    qDebug() << "finished: " << m_packetList.size();

    m_pullStream->init();
}

void MainWindow::showVideo(const QImage &image)
{
    ui->video_show->setPixmap(QPixmap::fromImage(image).scaled(
                              ui->video_show->size(), Qt::KeepAspectRatio, Qt::SmoothTransformation));
}

